<template>
    <div class="container-full">
        <div class="regedit-head">
            <h1 class="title">门店注册</h1>
            <span @click="$router.push('/login')" class="info-tip">已有登陆账号</span>
        </div>
        <div class="normal-form-container bottom-ash-line">
            <van-field type="tel" v-model="forma.phone" placeholder="请输入手机号（登陆账号）" :error-message="errorMsg.phone"/>
            <van-field v-model="forma.checkCode" :error-message="errorMsg.checkCode" placeholder="请输入验证码">
                <van-button slot="button" size="small" :disabled="this.countdown>0?true:false"
                            :error-message="errorMsg.checkCode" @click="sendMobileCode" type="primary"
                            class="check-button" round>{{countdownText}}
                </van-button>
            </van-field>
            <!--<van-field v-model="forma.name" :error-message="errorMsg.name" placeholder="请输入用户名" />-->
            <van-field v-model="forma.password" type="password" :error-message="errorMsg.password"
                       placeholder="请输入登录密码"/>
            <van-field v-model="forma.repassword" type="password" :error-message="errorMsg.repassword"
                       placeholder="请确认登录密码"/>
        </div>
        <div class="normal-form-container">
            <van-field v-model="forma.realname" placeholder="请输入联系人姓名" :error-message="errorMsg.realname"
                       class="el-mt-10"/>
            <van-field v-model="forma.shopName" placeholder="请输入门店名称" :error-message="errorMsg.shopName"/>
            <van-field v-model="forma.address" :error-message="errorMsg.address" placeholder="请输入门店所在详细地址">
                <van-button slot="button" size="small" @click="eventClickMapSelectAddress" type="primary"
                            class="map-button" round>地图选址
                </van-button>
            </van-field>
            <van-field v-model="forma.areaData" placeholder="点击选择门店所在地区（省/市/区县）" readonly
                       :error-message="errorMsg.area"/>
            <!--			 @click="showArea = true" -->
        </div>
        <div class="normal-form-button-container el-mt-30">
            <van-button type="primary" size="large" @click="onClickRegeditShop"
                        class="green-background font-size-17 edge-angle-normal">立即注册
            </van-button>
        </div>
        <van-popup position="bottom" v-model="showArea">
            <van-area :value="regionCode" :area-list="areaList" @confirm="confirmArea" @cancel="cancelArea"/>
        </van-popup>
    </div>
</template>

<script>
    import {Field, CellGroup, Button, Toast, Popup, Area, Dialog} from 'vant';

    import validator from '../../libs/js/validator.js';
    import areaList from '../../libs/js/area';

    export default {
        name: 'ShopIndex',
        components: {
            [Field.name]: Field,
            [CellGroup.name]: CellGroup,
            [Button.name]: Button,
            [Area.name]: Area,
            [Popup.name]: Popup
        },
        data() {
            return {
                countdown: 0,
                countdownText: '验证码',
                showArea: false,
                area: '',
                areaList: areaList,
                regionCode: '',
                forma: {
                    phone: '',
                    checkCode: '',
                    password: '',
                    repassword: '',
                    realname: '',
                    //name: '',
                    shopName: '',
                    address: '',
                    longitude: '',
                    latitude: '',
                    province: '',
                    city: '',
                    areaData: '',
                },
                errorMsg: {
                    phone: '',
                    checkCode: '',
                    password: '',
                    repassword: '',
                    realname: '',
                    name: '',
                    shopName: '',
                    area: '',
                    address: ''
                },
                rules: {
                    phone: [
                        {
                            validator: (rule, value, callback) => {
                                if (!value) {
                                    callback('请输入手机号码');
                                } else if (/^[1][0-9]{10}$/.test(value)) {
                                    callback();
                                } else {
                                    callback('请输入正确的手机号码');
                                }
                            }
                        }
                    ],
                    checkCode: [
                        {required: true, message: '请输入验证码'}
                    ],
                    password: [
                        {required: true, message: '请输入登录密码'}
                    ],
                    repassword: [
                        {required: true, message: '请输入确认登录密码'}
                    ],
                    //name: [
                    //    {required: true, message: '请输入用户名'}
                    //],
                    realname: [
                        {required: true, message: '请输入联系人姓名'}
                    ],
                    shopName: [
                        {required: true, message: '请输入门店名称'}
                    ],
                    area: [
                        {required: true, message: '请选择门店所在地区'}
                    ],
                    address: [
                        {required: true, message: '请输入门店所在详细地址'}
                    ],
                },
            }
        },
        created() {
            var forma = JSON.parse(localStorage.getItem('userRegedit'));
            if (forma) {
                this.forma = forma;
                localStorage.removeItem('userRegedit');
            }
            this.validator = validator(this.rules, this.forma);
            //   this.util = util();
        },
        mounted() {
            this.getAddress();

            if (this.$route.params.name) {
                // console.log(this.$route.params);

                this.forma.address = this.$route.params.address;

                let coordinate = String(this.$route.params.location).split(',');
                this.forma.longitude = coordinate[0];
                this.forma.latitude = coordinate[1];

                this.initializationLoadAmapSourceOperate({
                    longitude: coordinate[0], latitude: coordinate[1]
                }).then(
                    this.requestGetUserLocationData
                ).then(
                    (res) => {
                        console.log("getAddress  ", res);
                        var result = res.result,
                            {city, district, province, adcode} = result.regeocode.addressComponent;

                        this.forma.areaData = province + '-' + city + '-' + district;
                        this.regionCode = adcode;
                        this.forma.area = adcode;
                        this.forma.province = province;
                        this.forma.city = city;
                        // this.forma.province = province;
                        // console.log(result);
                    }
                ).catch(
                    (frs) => {
                        console.log(frs);
                    }
                );
            } else {
                this.initializationWeChatSDKEnvironment().then(
                    this.requestWeChatLocationInterface
                ).then(
                    (res) => {

                        console.log("getAddressWX  ", res);
                        /*	var result = res.result,
                                    { city, district, province, adcode } = result.regeocode.addressComponent;

                            this.forma.areaData = province + '-' + city + '-' + district;
                            */
                        this.forma.longitude = res.longitude;
                        this.forma.latitude = res.latitude;
                    }
                ).catch(
                    (frs) => {
                        console.log('wx-location-amap', frs);
                    }
                );
            }
        },
        methods: {
            getAddress() {
                this.$util.postRequestInterface('/api/citylist', {}, (res) => {
                    this.areaList = res.data;
                })
            },
            confirmArea(res) {
                this.showArea = false;
                this.forma.province = res[0].code;
                this.forma.city = res[1].code;
                this.forma.area = res[2].code;
                this.area = res[0].name + '-' + res[1].name + '-' + res[2].name;
            },
            cancelArea() {
                this.showArea = false;
            },
            /**
             * 清除验证提示
             * @param attrs
             */
            resetField(attrs) {
                attrs = !attrs ? Object.keys(this.errorMsg) : (Array.isArray(attrs) ? attrs : [attrs]);
                attrs.forEach(attr => {
                    this.errorMsg[attr] = ''
                })
            },
            validate(callback, data) {
                this.validator.validate((errors, fields) => {
                    this.resetField();
                    if (errors) {
                        fields.forEach(item => {
                            this.errorMsg[item.field] = item.message
                        })
                    }
                    callback && callback(errors, fields)
                }, data);
            },
            sendMobileCode() {
                this.validate(errors => {
                    if (!errors) {
                        let url = '/api/home/senMsg',
                            params = {
                                mobile: this.forma.phone
                            };
                        this.$util.postRequestInterface(url, params, (res) => {
                        });
                        this.countdown = 61;
                        this.countdownSubtract();
                    }
                }, 'phone')
            },
            countdownSubtract() {
                if (this.countdown > 0) {
                    setTimeout(() => {
                        this.countdown -= 1;
                        if (this.countdown > 0) {
                            this.countdownText = '倒计时' + this.countdown + 's';
                            this.countdownSubtract();
                        } else if (this.countdown == 0) {
                            this.countdownText = '验证码'
                        }
                    }, 1000)
                }
            },
            onClickRegeditShop() {
                var param = {
                    name: this.forma.phone,  // 此时全部都是手机号
                    realname: this.forma.realname,
                    phone: this.forma.phone,  //
                    zhicheng: this.forma.shopName,
                    province: this.forma.province,
                    city: this.forma.city,
                    county: this.forma.area,
                    address: this.forma.address,
                    longitude: this.forma.longitude,
                    latitude: this.forma.latitude,
                    code: this.forma.checkCode,
                    pwd: this.forma.repassword,
                    openid: 'shadow'
                };
                // console.log(param);
                // return;

                this.validate((errors, fields) => {
                    // console.log(errors);
                    if (!errors) {
                        if (this.forma.password != this.forma.repassword) {
                            Toast.fail('请确认登录密码');
                            return false;
                        }

                        this.$util.postRequestInterface('/api/add', param, (res) => {
                            Dialog.alert({
                                message: '注册成功,请等待管理员审核'
                            }).then(() => {
                                // on close
                                this.$router.push('/login');
                            });
                        });
                    }
                });
            },
            initializationLoadAmapSourceOperate(params) {
                return new Promise((resolve, reject) => {
                    resolve(params);

                    /*		this.$util.loadSourceUrl({
                                mode: 'script',
                                url: 'https://webapi.amap.com/maps?v=1.4.15&key=a9cee9141c7a483fe481b6d78f554f47&plugin=AMap.Geocoder',
                                name: 'gaode-map',
                                resolve: () => {
                                    resolve(params);
                                },
                                reject: reject
                            });*/
                });
            },
            requestGetUserLocationData(res) {
                return new Promise((resolve, reject) => {
                    if (!this.geocoder) {
                        this.geocoder = new AMap.Geocoder({
                            radius: 100,
                            extensions: "all"
                        });
                    }
                    // 将当前定位的坐标转换为地址信息
                    this.geocoder.getAddress([res.longitude, res.latitude], (status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            if (result.regeocode) {
                                // result.regeocode.formattedAddress
                                resolve({
                                    res, result
                                });
                            } else {
                                reject();
                            }
                        } else {
                            reject();
                        }
                    });
                });
            },
            eventClickMapSelectAddress() {
                window.localStorage.setItem('userRegedit', JSON.stringify(this.forma));
                this.$router.push('/public/map');
            },
            initializationWeChatSDKEnvironment() {
                return new Promise((resovle, reject) => {
                    this.$util.requestLoadWeChatSDKOperate(['checkJsApi', 'openLocation', 'getLocation']).then(
                        this.$util.requestWeChatAuthorizeDataset
                    ).then(
                        (res) => {
                            resovle();
                        }
                    ).catch(
                        (frs) => {
                            reject(frs);
                        }
                    );
                });
            },
            requestWeChatLocationInterface() {
                return new Promise((resolve, reject) => {
                    wx.getLocation({
                        // 默认为 wgs84 的 gps 坐标，如果要返回直接给 openLocation 用的火星坐标，可传入 gcj02
                        type: 'gcj02',
                        success: (res) => {
                            // res.longitude, res.latitude
                            resolve(res);
                        },
                        cancel: function (fres) {
                            // alert('用户拒绝授权获取地理位置');
                            reject(fres);
                        }
                    });
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
    .regedit-head {
        margin: 3.2rem 1.1rem 1.1rem;
        font-size: 1.6rem;

        display: flex;
        justify-content: space-between;
        align-items: flex-end;

        .title {
            margin: 0rem;
            padding: 0rem;
        }

        .info-tip {
            color: #666666;
            font-size: 1.4rem;
            padding-right: 1rem;
            position: relative;
        }

        .info-tip::after {
            content: "";
            display: block;
            width: 1rem;
            position: absolute;
            top: 0rem;
            bottom: 0rem;
            right: 0rem;
            background-image: url("../../../static/images/arrow-right-ash.png");
            background-repeat: no-repeat;
            background-position: center right;
            background-size: 50% 50%;
        }
    }

    .check-button {
        padding-left: 2rem !important;
        padding-right: 2rem !important;
        background-color: #ccffcc;
        color: #00cc00;
        font-size: 1.3rem;
    }

    .map-button {
        background-color: #00cc00;
        color: #ffffff;
        padding-left: 2rem !important;
        padding-right: 2rem !important;
        font-size: 1.3rem;
    }
</style>
